﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace RestaurateurConsole.Core
{
    [Serializable]
    public class BackupDB
    {
        public List<Customer> accounts = new List<Customer>();
        public List<Activity> activities = new List<Activity>();
        public List<Sale> sales = new List<Sale>();
        public List<SoldItem> solditems = new List<SoldItem>();
    }

    static class BackupHandler
    {
        static string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        static string Today = "Restaurateur Data Backup\\" + DateTime.Now.ToLongDateString().Replace("/", "-").Replace("\\", "-").Replace(":", "-");
        static string SerializedFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Restaurateur";
        static DishesHandler menuHandler = null;

        public static void Backup(Restaurateur DB, DishesHandler menu)
        {
            menuHandler = menu;
            Backup(DB);
        }

        public static void Backup(Restaurateur DB)
        {
            if (!Directory.Exists(Desktop + "\\" + Today))
            {
                Directory.CreateDirectory(Desktop + "\\" + Today);
                if (Directory.Exists(SerializedFilesPath))
                {
                    foreach (FileInfo f in new DirectoryInfo(SerializedFilesPath).GetFiles())
                    {
                        f.CopyTo(Desktop + "\\" + Today + "\\" + f.Name);
                    }

                    ExportMenuAsText(Desktop + "\\" + Today + "\\" + "Menu.txt");

                    BackupDB db = new BackupDB();
                    foreach (var v in DB.Sales)
                    {
                        db.sales.Add(new Sale() { Account = v.Account, Date = v.Date, Amount = v.Amount, SalesID = v.SalesID });
                    }
                    foreach (var v in DB.SoldItems)
                    {
                        db.solditems.Add(new SoldItem() { ItemName = v.ItemName, Price = v.Price, SalesID = v.SalesID, Quantity = v.Quantity, SoldItemsID = v.SoldItemsID });
                    }
                    foreach (var v in DB.Customers)
                    {
                        db.accounts.Add(new Customer() { CustomerID = v.CustomerID, CustomerName = v.CustomerName, CustomerPhone = v.CustomerPhone });
                    }
                    foreach (var v in DB.Activities)
                    {
                        db.activities.Add(new Activity() { ActivityID = v.ActivityID, CustID = v.CustID, Date = v.Date, Payment = v.Payment, Purchase = v.Purchase, SalesID = v.SalesID });
                    }
                    SerializationHandler serializer = new SerializationHandler(Desktop, Today, "Restaurateur.backupdb");
                    serializer.Serialize<BackupDB>(db);
                }
            }
        }

        public static void ExportMenu(string OutPath, DishesHandler menu)
        {
            if (menuHandler == null)
                menuHandler = menu;
            ExportMenuAsText(OutPath);
        }

        public static void ExportMenuAsText(string OutPath)
        {
            if (menuHandler != null)
            {
                FileStream menus;
                TextWriter tw = null;
                try
                {
                    menus = File.Open(OutPath, FileMode.Create, FileAccess.Write);
                    tw = new StreamWriter(menus);
                    foreach (var v in menuHandler.Dishes)
                    {
                        tw.WriteLine("{0}\t{1}", v.DishName, v.DishPrice);
                    }
                }
                catch (Exception x)
                {
                    throw x;
                }
                finally
                {
                    if (tw != null)
                        tw.Close();
                }
            }
        }

        public static void ExportCustAsText(string OutPath, IEnumerable<Customer> custs)
        {
            FileStream menus;
            TextWriter tw = null;
            try
            {
                menus = File.Open(OutPath, FileMode.Create, FileAccess.Write);
                tw = new StreamWriter(menus);
                foreach (var v in custs)
                {
                    tw.WriteLine("{0}\t{1}\t{2}", v.CustomerID, v.CustomerName, v.CustomerPhone);
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                if (tw != null)
                    tw.Close();
            }
        }

        public static void ExportSaleAsText(string OutPath, IEnumerable<Sale> custs)
        {
            FileStream menus;
            TextWriter tw = null;
            try
            {
                menus = File.Open(OutPath, FileMode.Create, FileAccess.Write);
                tw = new StreamWriter(menus);
                foreach (var v in custs)
                {
                    tw.WriteLine("{0}\t{1}\t{2}\t{3}", v.SalesID, v.Date, v.Amount, v.Account);
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                if (tw != null)
                    tw.Close();
            }
        }

        public static void ExportTransactionsAsText(string OutPath, IEnumerable<XAction> custs)
        {
            FileStream menus;
            TextWriter tw = null;
            try
            {
                menus = File.Open(OutPath, FileMode.Create, FileAccess.Write);
                tw = new StreamWriter(menus);
                foreach (var v in custs)
                {
                    tw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}", v.TransactionDate, v.DepositAmount, v.DepositType, v.DepositComment, v.PayerName, v.WithdrawAmount, v.WithdrawType, v.WithdrawComment, v.PayeeName, v.ClosingBalance);
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                if (tw != null)
                    tw.Close();
            }
        }

        public static BackupDB ViewBackupDB(string path)
        {
            SerializationHandler deserializer = new SerializationHandler(path, "Restaurateur.backupdb");
            return deserializer.DeSerialize<BackupDB>();
        }

        public static void ResetDatabase(Restaurateur Db)
        {
            Db.Customers.DeleteAllOnSubmit(Db.Customers.AsEnumerable());
            Db.Sales.DeleteAllOnSubmit(Db.Sales.AsEnumerable());
            Db.Activities.DeleteAllOnSubmit(Db.Activities.AsEnumerable());
            Db.SoldItems.DeleteAllOnSubmit(Db.SoldItems.AsEnumerable());
            Db.SubmitChanges();
        }
    }
}
